import os
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, 
                             QFileDialog, QCheckBox, QSpinBox, QLineEdit, QGroupBox,
                             QProgressBar, QMessageBox)
from PyQt5.QtCore import Qt
from ffmpeg_liber import FFmpegProcessor

def create_merge_page(main_window):
    """创建左右眼合并页面"""
    merge_widget = QWidget()
    merge_widget.setObjectName("tab_content")
    merge_layout = QVBoxLayout(merge_widget)
    merge_layout.setSpacing(15)
    merge_layout.setContentsMargins(20, 20, 20, 20)
    
    # 初始化属性
    main_window.left_eye_video = ""
    main_window.right_eye_video = ""
    main_window.output_video = ""
    
    # 左右眼视频选择
    videos_group = QGroupBox("左右眼视频")
    videos_layout = QVBoxLayout(videos_group)
    
    left_video_layout = QHBoxLayout()
    left_video_label = QLabel("左眼视频:")
    main_window.left_video_edit = QLineEdit()
    main_window.left_video_edit.setReadOnly(True)
    left_video_btn = QPushButton("浏览...")
    left_video_btn.clicked.connect(lambda: select_left_video(main_window))
    
    left_video_layout.addWidget(left_video_label)
    left_video_layout.addWidget(main_window.left_video_edit)
    left_video_layout.addWidget(left_video_btn)
    
    right_video_layout = QHBoxLayout()
    right_video_label = QLabel("右眼视频:")
    main_window.right_video_edit = QLineEdit()
    main_window.right_video_edit.setReadOnly(True)
    right_video_btn = QPushButton("浏览...")
    right_video_btn.clicked.connect(lambda: select_right_video(main_window))
    
    right_video_layout.addWidget(right_video_label)
    right_video_layout.addWidget(main_window.right_video_edit)
    right_video_layout.addWidget(right_video_btn)
    
    # 添加输出视频路径设置
    output_layout = QHBoxLayout()
    output_label = QLabel("输出视频:")
    main_window.output_path_edit = QLineEdit()  # 这行应该在函数内部，不是模块级别
    main_window.output_path_edit.setReadOnly(True)
    output_btn = QPushButton("浏览...")
    output_btn.clicked.connect(lambda: select_output_path(main_window))
    
    output_layout.addWidget(output_label)
    output_layout.addWidget(main_window.output_path_edit)
    output_layout.addWidget(output_btn)
    
    # 将输出视频路径布局添加到视频组
    videos_layout.addLayout(left_video_layout)
    videos_layout.addLayout(right_video_layout)
    videos_layout.addLayout(output_layout)
    
    # 黑色线条设置
    line_layout = QHBoxLayout()
    main_window.black_line_check = QCheckBox("添加黑色分隔线")
    line_width_label = QLabel("线条宽度:")
    main_window.line_width_spin = QSpinBox()
    main_window.line_width_spin.setRange(1, 100)
    main_window.line_width_spin.setValue(20)
    
    line_layout.addWidget(main_window.black_line_check)
    line_layout.addWidget(line_width_label)
    line_layout.addWidget(main_window.line_width_spin)
    line_layout.addStretch()
    
    # 添加到视频组
    videos_layout.addLayout(line_layout)
    
    # 进度条区域
    progress_layout = QHBoxLayout()
    progress_label = QLabel("合并进度:")
    main_window.merge_progress_bar = QProgressBar()
    main_window.merge_progress_bar.setRange(0, 100)
    main_window.merge_progress_bar.setValue(0)
    
    progress_layout.addWidget(progress_label)
    progress_layout.addWidget(main_window.merge_progress_bar)
    
    # 按钮区域
    buttons_layout = QHBoxLayout()
    main_window.merge_start_btn = QPushButton("合并")
    main_window.merge_cancel_btn = QPushButton("取消")
    
    main_window.merge_start_btn.clicked.connect(lambda: start_merging(main_window))
    main_window.merge_cancel_btn.clicked.connect(lambda: cancel_merging(main_window))
    
    buttons_layout.addStretch()
    buttons_layout.addWidget(main_window.merge_start_btn)
    buttons_layout.addWidget(main_window.merge_cancel_btn)
    
    # 添加到主布局
    merge_layout.addWidget(videos_group)
    merge_layout.addLayout(progress_layout)
    merge_layout.addLayout(buttons_layout)
    merge_layout.addStretch()
    
    # 添加到标签页
    main_window.content_stack.addTab(merge_widget, "左右眼合并")
    
    # 初始状态
    main_window.merge_cancel_btn.setEnabled(False)
    
    return merge_widget

# 以下是辅助函数
def select_left_video(main_window):
    """选择左眼视频"""
    file_dialog = QFileDialog(main_window)
    file_dialog.setWindowTitle("选择左眼视频")
    file_dialog.setNameFilter("视频文件 (*.mp4 *.avi *.mkv *.mov)")
    file_dialog.setFileMode(QFileDialog.ExistingFile)
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            left_video = selected_files[0]
            main_window.left_eye_video = left_video
            main_window.left_video_edit.setText(left_video)
            main_window.append_log(f"已选择左眼视频: {left_video}")

def select_right_video(main_window):
    """选择右眼视频"""
    file_dialog = QFileDialog(main_window)
    file_dialog.setWindowTitle("选择右眼视频")
    file_dialog.setNameFilter("视频文件 (*.mp4 *.avi *.mkv *.mov)")
    file_dialog.setFileMode(QFileDialog.ExistingFile)
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            right_video = selected_files[0]
            main_window.right_eye_video = right_video
            main_window.right_video_edit.setText(right_video)
            main_window.append_log(f"已选择右眼视频: {right_video}")

def select_output_path(main_window):
    """选择输出视频路径"""
    file_dialog = QFileDialog(main_window)
    file_dialog.setWindowTitle("设置输出视频")
    file_dialog.setNameFilter("视频文件 (*.mp4)")
    file_dialog.setAcceptMode(QFileDialog.AcceptSave)
    
    # 如果已经选择了左眼视频，默认输出到同一目录
    if main_window.left_eye_video:
        default_dir = os.path.dirname(main_window.left_eye_video)
        default_file = os.path.join(default_dir, "3D_output.mp4")
        file_dialog.selectFile(default_file)
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            output_path = selected_files[0]
            # 确保文件扩展名为.mp4
            if not output_path.lower().endswith('.mp4'):
                output_path += '.mp4'
            main_window.output_video = output_path
            main_window.output_path_edit.setText(output_path)
            main_window.append_log(f"已设置输出视频: {output_path}")

def start_merging(main_window):
    """开始合并左右眼视频"""
    # 检查是否已设置FFmpeg路径
    if not main_window.ffmpeg_path or not os.path.exists(main_window.ffmpeg_path):
        QMessageBox.warning(main_window, "警告", "请先设置FFmpeg路径")
        return
    
    # 检查是否已选择左右眼视频
    if not main_window.left_eye_video or not os.path.exists(main_window.left_eye_video):
        QMessageBox.warning(main_window, "警告", "请先选择左眼视频")
        return
    
    if not main_window.right_eye_video or not os.path.exists(main_window.right_eye_video):
        QMessageBox.warning(main_window, "警告", "请先选择右眼视频")
        return
    
    # 检查是否已设置输出视频
    if not hasattr(main_window, 'output_video') or not main_window.output_video:
        # 默认输出到左眼视频所在目录
        output_dir = os.path.dirname(main_window.left_eye_video)
        main_window.output_video = os.path.join(output_dir, "3D_output.mp4")
        if hasattr(main_window, 'output_path_edit'):
            main_window.output_path_edit.setText(main_window.output_video)
    
    # 禁用按钮
    main_window.merge_start_btn.setEnabled(False)
    main_window.merge_cancel_btn.setEnabled(True)
    
    # 获取合并选项
    black_line = main_window.black_line_check.isChecked()
    black_line_width = main_window.line_width_spin.value()
    
    # 直接使用main_window.ffmpeg_accel作为硬件加速选项
    hw_accel = main_window.ffmpeg_accel
    main_window.append_log(f"使用硬件加速: {hw_accel}")
    
    # 使用FFmpeg线程来合并视频
    main_window.ffmpeg_thread = FFmpegProcessor(main_window.ffmpeg_path, hw_accel)
    
    # 设置合并参数
    main_window.ffmpeg_thread.left_eye_video = main_window.left_eye_video
    main_window.ffmpeg_thread.right_eye_video = main_window.right_eye_video
    main_window.ffmpeg_thread.output_video = main_window.output_video
    main_window.ffmpeg_thread.black_line = black_line
    main_window.ffmpeg_thread.black_line_width = black_line_width
    main_window.ffmpeg_thread.operation_type = "merge_videos"
    
    # 连接信号
    main_window.ffmpeg_thread.progress_updated.connect(lambda p: update_progress(main_window, p))
    main_window.ffmpeg_thread.log_message.connect(main_window.append_log)
    main_window.ffmpeg_thread.process_completed.connect(lambda success, msg: on_merge_completed(main_window, success, msg))
    
    # 启动线程
    main_window.append_log("开始合并左右眼视频...")
    main_window.ffmpeg_thread.start()

def cancel_merging(main_window):
    """取消合并操作"""
    if hasattr(main_window, 'ffmpeg_thread') and main_window.ffmpeg_thread.isRunning():
        main_window.ffmpeg_thread.should_stop = True
        main_window.append_log("正在取消合并操作...")
    
    main_window.merge_start_btn.setEnabled(True)
    main_window.merge_cancel_btn.setEnabled(False)

def update_progress(main_window, progress):
    """更新进度条"""
    main_window.merge_progress_bar.setValue(progress)

def on_merge_completed(main_window, success, message):
    """合并完成回调"""
    main_window.merge_start_btn.setEnabled(True)
    main_window.merge_cancel_btn.setEnabled(False)
    
    if success:
        main_window.append_log(f"合并成功: {message}")
        QMessageBox.information(main_window, "成功", f"左右眼视频合并成功!\n输出文件: {main_window.output_video}")
    else:
        main_window.append_log(f"合并失败: {message}")
        QMessageBox.warning(main_window, "失败", f"左右眼视频合并失败: {message}")